<?php

namespace app\api\service;

use app\admin\model\Userconsumedetail;
use app\common\Helper;

use app\common\model\Userreceivetic;
use app\admin\model\Ticket;
use app\admin\model\Storeuser;
use think\Db;
use think\Exception;
use think\Loader;
use think\Log;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

/**
 * 处理微信支付回调
 * Class WxNotify
 * @package app\api\service
 */
class WxNotify extends \WxPayNotify{

    //<xml>
    //<appid><![CDATA[wx2421b1c4370ec43b]]></appid>
    //<attach><![CDATA[支付测试]]></attach>
    //<bank_type><![CDATA[CFT]]></bank_type>
    //<fee_type><![CDATA[CNY]]></fee_type>
    //<is_subscribe><![CDATA[Y]]></is_subscribe>
    //<mch_id><![CDATA[10000100]]></mch_id>
    //<nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
    //<openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
    //<out_trade_no><![CDATA[1409811653]]></out_trade_no>
    //<result_code><![CDATA[SUCCESS]]></result_code>
    //<return_code><![CDATA[SUCCESS]]></return_code>
    //<sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>
    //<sub_mch_id><![CDATA[10000100]]></sub_mch_id>
    //<time_end><![CDATA[20140903131540]]></time_end>
    //<total_fee>1</total_fee>
    //<trade_type><![CDATA[JSAPI]]></trade_type>
    //<transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
    //</xml>
    public function NotifyProcess($data, &$msg){
        if($data['result_code'] == 'SUCCESS'){
            $orderNo = $data['out_trade_no'];
            $paytime = self::timeFormat($data['time_end']);
            Db::startTrans();
            try
            {
                /**
                 * 1.修改订单支付状态
                 * 2.storecustradedetail(店铺客户交易明细表，插入一条记录，减去平台抽成和一二级分销)
                 * 3.platformearn(根据平台抽成规则，插入一条记录)
                 * 3.一二级分销抽成
                 * 4.我的优惠券插入记录
                 */
                $order = Userconsumedetail::where('orderNo',$orderNo)->lock(true)->find();
                if($order->currentStatus == 0){
                    Userconsumedetail::where('id',$order->id)->update(['currentStatus'=>1,'payTime'=>$paytime]);
                    //网店铺客户关系表中插入一条数据
                    $this->insertStoreuser($order);
                    if($order->orderSource == 1){
                        //购买优惠券
                        //我的优惠券里插入一条记录
                        $this->insertUserreceivetic($order,$paytime);
                    }elseif ($order->orderSource == 2){
                        //使用优惠券付款
                        //更新我的优惠券状态
                        $this->updateuserreceivetic($order->receiveticId,$paytime);
                    }else{
                        //todo
                    }

                }
                Db::commit();
                return true;
            }catch (Exception $ex){
                Db::rollback();
                Log::record($ex);
                return false;
            }
        }else{
            return true;
        }
    }

    private function insertStoreuser($order){
        $Storeuser = Storeuser::where(['userId'=>$order->userId,'storeId'=>$order->storeId])->find();
        if(!$Storeuser){
            $StoreuserModel = new Storeuser();
            $StoreuserModel->userId = $order->userId;
            $StoreuserModel->storeId = $order->storeId;
            $StoreuserModel->save();
        }
    }

    private function insertUserreceivetic($order,$paytime){
       $Userreceivetic = new Userreceivetic();
        $Userreceivetic->id = Helper::getUUID();
        $Userreceivetic->userId = $order->userId;
        $Userreceivetic->storeId = $order->storeId;
        $Userreceivetic->ticketId = $order->ticketId;
        $Userreceivetic->receiveTicketTime = $paytime;
        $Userreceivetic->save();
        //优惠券的剩余数量减1
        Ticket::where('id',$order->ticketId)->setDec('remainGross',1);
    }

    private function updateuserreceivetic($id,$paytime){
        $Userreceivetic = Userreceivetic::get($id);
        $Userreceivetic->status = 1;
        $Userreceivetic->useTime = $paytime;
        $Userreceivetic->save();
    }

    public static function timeFormat($time){
        $paytime = substr($time,0,4).'-';
        $paytime .= substr($time,4,2).'-';
        $paytime .= substr($time,6,2);
        $paytime .= ' ';
        $paytime .= substr($time,8,2).':';
        $paytime .= substr($time,10,2).':';
        $paytime .= substr($time,12,2);
        $paytime = date('Y-m-d H:i:s',strtotime($paytime));

        return $paytime;
    }

}